﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using EnvDTE;
using System.IO;
using System.Threading;

using EnvDTE80;
//using Microsoft.VisualStudio.CommandBars;

namespace CodeBuilder.Automation
{
    using CodeBuilder.ServiceReference;
    using CodeBuilder.Controls;
    public partial class CodeBuildForm : Form
    {
        public CodeBuildForm()
        {
            InitializeComponent();
        }

        private void CodeBuildForm_Load(object sender, EventArgs e)
        {
            try
            {
                LoadTables();
                LoadProjects();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载解决方案信息出现错误！"+ex.Message);
            }
        }

        private List<Table> _tabs = null;
        private List<Table> GetTables()
        {
            if (_tabs == null)
            {
                DataBaseClient service = ServiceHost.Instance;
                _tabs = service.GetObjects(ObjectType.Table);
            }
            return _tabs;
        }

        string _bussinessName = string.Empty;
        public string BussinessName
        {
            get {
                if (string.IsNullOrEmpty(_bussinessName))
                {
                    DataBaseClient service = ServiceHost.Instance;
                    _bussinessName = service.GetBussinessName();
                }
                return _bussinessName;
            }
        }

        /// <summary>
        /// 加载数据表
        /// </summary>
        private void LoadTables()
        {
            List<Table> items = GetTables();
            IOrderedEnumerable<Table> tabs = items.OrderBy(t => t.Name);

            treeView_Tables.Nodes.Clear();
            treeView_Tables.Tag = tabs;
            foreach (Table tab in tabs)
            {
                TreeNode node = new TreeNode();
                node.Text = string.Format("{0}{1}", tab.Name, !string.IsNullOrEmpty(tab.Description) ? "[" + tab.Description + "]" : string.Empty);
                node.Tag = tab.Name;
                treeView_Tables.Nodes.Add(node);
            }
        }

        /// <summary>
        /// 加载工程解决方案
        /// </summary>
        private void LoadProjects()
        {
            dgv_Models.Rows.Clear();
            dgv_Models.AutoGenerateColumns = false;
            

            List<CodeModel> models = GetModels();
            //判断Project 
            dgv_Models.DataMember = "models";
            dgv_Models.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgv_Models_DataBindingComplete);

            dgv_Models.DataSource = models;

        }

        /// <summary>
        /// 获取当前解决方案的项目工程（排除解决方案文件夹）
        /// </summary>
        /// <returns></returns>
        private List<object> GetCurrentSolutionProject()
        {
            List<object> projList = new List<object>();
            Solution2 soln = (Solution2)EnvConfig.ApplicationObject.Solution;
            //获取解决方案列表
            Projects projs = soln.Projects;
            if (projs.Count > 0)
            {
                List<CodeModel> models= GetModels();

                models.ForEach(t =>
                {
                    object projObj = GetSolutionProject(projs, t);

                    if (projObj!=null)
                    {
                        projList.Add(projObj);
                    }
                });
            }
            return projList;
        }

        private ProjectItem GetSolutionProject(ProjectItem pi, CodeModel model)
        {
            if (pi!=null &&  pi.ProjectItems!=null && pi.ProjectItems.Count > 0)
            {
                for (int i = 1; i <= pi.ProjectItems.Count; i++)
                {
                    ProjectItem item = pi.ProjectItems.Item(i);
                    if (item.Name.ToLower().Contains(model.ProjectName.ToLower()) && item.Name.Contains(ConstPoint))
                    {
                        return item;
                    }
                    else
                    {
                        ProjectItem newItem = GetSolutionProject(item, model);
                        if (newItem!=null)
                        {
                            return newItem;
                        }
                    }
                }
            }
            return null;
        }


        private ProjectItem GetSolutionProject(ProjectItems piList, CodeModel model)
        {
            if (piList.Count > 0)
            {
                for (int i = 1; i <= piList.Count; i++)
                {
                    ProjectItem item = piList.Item(i);
                    if (item.Name.ToLower().Contains(model.ProjectName.ToLower()) && item.Name.Contains(ConstPoint))
                    {
                        return item;
                    }
                    else
                    {
                        ProjectItem newItem = GetSolutionProject(item, model);
                        if (newItem != null)
                        {
                            return newItem;
                        }
                    }
                }
            }
            return null;
        }

        private const string ConstPoint = ".";

        private object GetSolutionProject(Projects projs, CodeModel model)
        {
            if (projs.Count > 0)
            {
                for (int i = 1; i <= projs.Count; i++)
                {
                    Project proj = projs.Item(i);
                    if (proj.Name.ToLower().Contains(model.ProjectName.ToLower()) && proj.Name.Contains(ConstPoint))
                    {
                        return proj;
                    }
                    else if (proj.ProjectItems != null && proj.ProjectItems.Count > 0)
                    {
                        //查找子节点
                        ProjectItem newItem = GetSolutionProject(proj.ProjectItems, model);
                        if (newItem != null)
                        {
                            return newItem;
                        }
                    }
                }
            }
            return string.Empty;
        }

        public Solution2 Solution
        {
            get
            {
                return (Solution2)EnvConfig.ApplicationObject.Solution;
            }
        }

        void dgv_Models_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

            Solution2 soln = this.Solution;
            //获取解决方案列表
            Projects projList = soln.Projects;
            if (projList.Count == 0)
            {
                ShowMsg("请先打开解决方案！");                
                return;
            }

            //绑定 解决方案下拉
            List<object> items = GetCurrentSolutionProject();
            items.ForEach(t => {
                if (t is Project)
                {
                    Project item = t as Project;
                    Col_Solution.Items.Add(item.Name);
                }
                else if (t is ProjectItem)
                {
                    ProjectItem item = t as ProjectItem;
                    Col_Solution.Items.Add(item.Name);
                }
               
            });

           

            //设置默认选择项
            List<CodeModel> models = GetModels();

            foreach (DataGridViewRow row in dgv_Models.Rows)
            {
                DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells["Col_Solution"];
                //获取模型名称
                string modelName = row.Cells["Col_Name"].Value.ToString();
                CodeModel findModel = models.FirstOrDefault(t=>t.ModelName.Equals(modelName));
                
                for (int i = 0; i < cell.Items.Count; i++)
                {
                  string projectName =  cell.Items[i].ToString();
                  if (projectName.ToLower().Contains(findModel.ProjectName.ToLower()))
                  {
                      //设置默认工程
                      cell.Value = projectName;                      
                      break;
                  }
                }


            }
        }

        private void ShowMsg(string msg)
        {            
            this.toolStatusMsg.Text = msg;
        }

        private void ShowMsg(string format,params object [] paras)
        {
            ShowMsg(string.Format(format, paras));
        }

        private List<CodeModel> _models = null;
        private List<CodeModel> GetModels()
        {
            if (_models == null)
            {
                List<CodeModel> models = new List<CodeModel>();

                //models.Add(new CodeModel { ModelName = CodeType.SqlServerData, ProjectName = "SqlServer.Data" , IsSelect=true});
                models.Add(new CodeModel { ModelName = CodeType.SqlServerBusinessImplement, ProjectName = "SqlServer.BusinessImplement", IsSelect = true });
                models.Add(new CodeModel { ModelName = CodeType.DataExchange, ProjectName = "DataExchange", IsSelect = true });
                models.Add(new CodeModel { ModelName = CodeType.DataContract, ProjectName = "DataContract", IsSelect = true });
                models.Add(new CodeModel { ModelName = CodeType.ServiceContract, ProjectName = "ServiceContract", IsSelect = true });
                models.Add(new CodeModel { ModelName = CodeType.ServiceImplement, ProjectName = "ServiceImplement", IsSelect = true });
                models.Add(new CodeModel { ModelName = CodeType.CoreService, ProjectName = "CoreService", IsSelect = true });
                models.Add(new CodeModel { ModelName = CodeType.Web, ProjectName = "Web", IsSelect = true });


                _models = models;
            }
            return _models;
        }

        /// <summary>
        /// 全选数据表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_Tables_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < treeView_Tables.Nodes.Count; i++)
            {
                treeView_Tables.Nodes[i].Checked = checkBox_Tables.Checked;
            }
        }

        /// <summary>
        /// 全选模型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_Model_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dgv_Models.Rows)
            {
                row.Cells["Col_Select"].Value = checkBox_Model.Checked;               
            }
        }

        /// <summary>
        /// 生成代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                CreateCodeToSolution();
                //System.Threading.Thread thread = new System.Threading.Thread(new ThreadStart(CreateCodeToSolution));
                //thread.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void CreateCodeToSolution()
        {
            //获取解决方案列表
            List<object> projs = GetCurrentSolutionProject();

            List<CodeModel> models = GetSelectModels();
            List<string> tables = GetSelectTables();
            List<Table> tabs = GetSelectTables(tables);

            bool isWriteToProject = checkBox_WriteToProject.Checked;
            if (IsValidate(models, tables))
            {
                //开始生成代码。
                CodeBuild(projs, tabs, models, isWriteToProject);
            }
        }

        /// <summary>
        /// 开始生成代码
        /// </summary>
        /// <param name="projList"></param>
        /// <param name="tables"></param>
        /// <param name="models"></param>
        private void CodeBuild(List<object> projList, List<Table> tables, List<CodeModel> models,bool isWrite)
        {
            toolProgressBar.Maximum = models.Count;
            for (int i = 0; i < models.Count;i++ )
            {
                CodeModel v = models[i];
                CodeBuild(GetProject(projList, v.ProjectName), tables, v.ModelName, isWrite);
                toolProgressBar.Value = (i+1);
            }
            MessageBox.Show("生成完毕！");
        }


        private Project GetProject(List<object> projList, string projectName)
        {
            for (int i = 0; i < projList.Count; i++)
            {
                object t = projList[i];
                
                if (t is Project)
                {
                    Project item = t as Project;
                    if (item.Name.Equals(projectName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        return item;
                    }
                }
                else if (t is ProjectItem)
                {
                    ProjectItem item = t as ProjectItem;
                    if (item.Name.Equals(projectName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        return item.SubProject;
                    }
                }

            }
            return null;
        }
        private void CodeBuild(Project proj, List<Table> tables, string modelName,bool isWrite)
        {
            
            switch (modelName)
            {
                case CodeType.SqlServerData:
                    CreateCodeForSqlServerData(proj, tables);
                    break;
                case CodeType.SqlServerBusinessImplement:
                    CreateCodeForSqlServerBussinessImplement(proj, tables, isWrite);
                    break;
                case CodeType.DataExchange:
                    CreateCodeForDataExchange(proj, tables, isWrite);
                    break;
                case CodeType.DataContract:
                    CreateCodeForDataContract(proj, tables, isWrite);
                    break;
                case CodeType.ServiceContract:
                    CreateCodeForServiceContract(proj, tables, isWrite);
                    break;
                case CodeType.ServiceImplement:
                    CreateCodeForServiceImplement(proj, tables, isWrite);
                    break;
                case CodeType.CoreService:
                    CreateCodeForCoreService(proj, tables, isWrite);
                    break;
                case CodeType.Web:
                    CreateCodeForWeb(proj, tables, isWrite);
                    break;
                default:
                    break;
            }
        }

        #region CodeBuild
        private void WriteFile(string fileName,string data)
        {
            using (StreamWriter sw = new StreamWriter(fileName,false,Encoding.Default))
            {
                sw.Write(data);
            }
        }

       
        private string DirectoryPath
        {
            get
            {
                return string.Format(@"{0}\CodeGenerate\{1}\",Environment.CurrentDirectory,DateTime.Now.ToString("yyyy-MM-dd"));
            }
        }

        private string GetProjectPath(Project proj)
        {
            return Path.GetDirectoryName(proj.FullName);
        }

        private string GetFileName(string path)
        {
            string temp = path;
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            if (File.Exists(path))
            {
                //更改文件名
                temp = string.Format(@"{0}\{1}_{2}{3}", Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path), DateTime.Now.ToString("yyMMddhhmmss"), Path.GetExtension(path));
            }
            return temp;
        }

        /// <summary>
        /// 获取 选择数据表 实体对象列表
        /// </summary>
        /// <param name="tables"></param>
        /// <returns></returns>
        private List<Table> GetSelectTables(List<string> tables)
        {
            List<Table> tabs = GetTables();
            List<Table> newTabs = new List<Table>();
            tables.ForEach(t => {
               Table findTab =  tabs.FirstOrDefault(q => q.Name.Equals(t));
               if (findTab != null)
               {
                   newTabs.Add(findTab);
               }
            });
            return newTabs;
        }

        /// <summary>
        /// 合并模式全选所有列 和 where 语句。
        /// </summary>
        /// <param name="cols"></param>
        private void ConvertColumnsToSelectAndWhere(List<Column> cols)
        {
            for (int i = 0; i < cols.Count; i++)
            {
                Column col = cols[i];
                col.IsSelect = true;
                col.IsWhere = true;
            }
        }

        private string ConvertResult(string code)
        {
            return code.Replace("*Author*", Config.Author);
        }

        private void CreateCodeForSqlServerData(Project proj, List<Table> tables)
        {
                       
        }

        /// <summary>
        /// 生成SqlServer Bussiness层
        /// </summary>
        /// <param name="proj"></param>
        /// <param name="tables"></param>
        private void CreateCodeForSqlServerBussinessImplement(Project proj, List<Table> tables, bool isWrite)
        {
            DataBaseClient service = ServiceHost.Instance;

            tables.ForEach(t =>
            {
                List<Column> cols = service.GetColumns(t.Name);
                //选择所有列
                ConvertColumnsToSelectAndWhere(cols);

                string bussinessCode = ConvertResult(service.CreateBussinessImplement(t));

                //合并输出
                bussinessCode = bussinessCode.Replace("{*bussinessquery*}", service.CreateServicePageList(t, cols));

                string pageName = service.GetCodeFileName(t.Name, PageType.SqlServerBussinessImplement);
                string path = GetFileName(string.Format(@"{0}\{1}.cs", GetProjectPath(proj), pageName));
                WriteFile(path, bussinessCode);
                if (isWrite)
                {
                    proj.ProjectItems.AddFromFile(path);
                }
                ShowMsg("{0} {1} SqlServer.BussinessImplement 生成完毕。",t.Name,t.Description);
                
            });           
        }

        /// <summary>
        /// 数据交换层
        /// </summary>
        /// <param name="proj"></param>
        /// <param name="tables"></param>
        private void CreateCodeForDataExchange(Project proj, List<Table> tables, bool isWrite)
        {
            DataBaseClient service = ServiceHost.Instance;

            tables.ForEach(t =>
            {
                List<Column> cols = service.GetColumns(t.Name);
                //选择所有列
                ConvertColumnsToSelectAndWhere(cols);

                string exchangeCode = ConvertResult(service.CreateDataExchange(t, cols));
                string pageName = service.GetCodeFileName(t.Name, PageType.SqlServerDataExchage);
                string path = GetFileName(string.Format(@"{0}\{1}.cs", GetProjectPath(proj), pageName));
                WriteFile(path, exchangeCode);
                if (isWrite)
                {
                    proj.ProjectItems.AddFromFile(path);
                }
                ShowMsg("{0} {1} SqlServer.DataExchange 生成完毕。", t.Name, t.Description);

            });           
        }

        private void CreateCodeForDataContract(Project proj, List<Table> tables, bool isWrite)
        {
            DataBaseClient service = ServiceHost.Instance;

            tables.ForEach(t =>
            {
                List<Column> cols = service.GetColumns(t.Name);
                //选择所有列
                ConvertColumnsToSelectAndWhere(cols);


                string sCode = ConvertResult(service.CreateDataContract(t, cols));
                string pageName = service.GetCodeFileName(t.Name, PageType.DataContract);

                string path = GetFileName(string.Format(@"{0}\{1}.cs", GetProjectPath(proj), pageName));
                WriteFile(path, sCode);
                if (isWrite)
                {
                    proj.ProjectItems.AddFromFile(path);
                }

                //生成CmdObject文件
                sCode = ConvertResult(service.CreateServiceCmdObject(t,cols));
                pageName = service.GetCodeFileName(t.Name, PageType.DataContract);
                path = GetFileName(string.Format(@"{0}\CmdObject\{1}CmdObject.cs", GetProjectPath(proj), pageName));
                WriteFile(path, sCode);
                if (isWrite)
                {
                    //添加至解决方案
                    proj.ProjectItems.AddFromFile(path);
                }

                ShowMsg("{0} {1} DataContract 生成完毕。", t.Name, t.Description);

            });           
        }

        private void CreateCodeForServiceContract(Project proj, List<Table> tables, bool isWrite)
        {
            DataBaseClient service = ServiceHost.Instance;

            tables.ForEach(t =>
            {
                List<Column> cols = service.GetColumns(t.Name);
                //选择所有列
                ConvertColumnsToSelectAndWhere(cols);

                string sCode = ConvertResult(service.CreateServiceContract(t, cols));
                string pageName = service.GetCodeFileName(t.Name, PageType.ServiceContract);

                string path = GetFileName(string.Format(@"{0}\{1}.cs", GetProjectPath(proj), pageName));
                WriteFile(path, sCode);
                if (isWrite)
                {
                    proj.ProjectItems.AddFromFile(path);
                }
                ShowMsg("{0} {1} ServiceContract 生成完毕。", t.Name, t.Description);

            });           
        }

        private void CreateCodeForServiceImplement(Project proj, List<Table> tables, bool isWrite)
        {
            DataBaseClient service = ServiceHost.Instance;

            tables.ForEach(t =>
            {
                List<Column> cols = service.GetColumns(t.Name);
                //选择所有列
                ConvertColumnsToSelectAndWhere(cols);

                string sCode = ConvertResult(service.CreateServiceImplement(t, cols));
                string pageName = service.GetCodeFileName(t.Name, PageType.ServiceImplete);

                string path = GetFileName(string.Format(@"{0}\{1}.cs", GetProjectPath(proj), pageName));
                WriteFile(path, sCode);
                if (isWrite)
                {
                    proj.ProjectItems.AddFromFile(path);
                }
                ShowMsg("{0} {1} ServiceImplement 生成完毕。", t.Name, t.Description);

            });           
        }

        private void CreateCodeForCoreService(Project proj, List<Table> tables, bool isWrite)
        {
            if (isWrite)
            {
                string path = string.Format(@"{0}\ServiceManager.cs", GetProjectPath(proj));

                string csContent = string.Empty;
                using (StreamReader sr = new StreamReader(path, Encoding.Default))
                {
                    csContent = sr.ReadToEnd();
                }

                //写入文件
                 DataBaseClient service = ServiceHost.Instance;

                 tables.ForEach(t =>
                 {
                     string code = service.CreateCoreService(t);
                     if (csContent.IndexOf(code) < 0)
                     {
                         //不存在 即写入
                         int lastIndex = csContent.LastIndexOf("}");
                         int lastsencond = csContent.Substring(0, lastIndex).LastIndexOf("}");

                        csContent = csContent.Insert(lastsencond, code+Environment.NewLine);
                     }
                 });

                //写入文件
                 using (StreamWriter sw = new StreamWriter(path, false, Encoding.Default))
                 {
                     sw.Write(csContent);
                 }

                 ShowMsg("CoreService 生成完毕。");
                

            }
        }

        private void CreateCodeForWeb(Project proj, List<Table> tables, bool isWrite)
        {
            DataBaseClient service = ServiceHost.Instance;

            tables.ForEach(t =>
            {
                List<Column> cols = service.GetColumns(t.Name);

                //选择所有列
                ConvertColumnsToSelectAndWhere(cols);

                string aspxcode = ConvertResult(service.CreateAspx(t));
                //合并
                aspxcode = aspxcode.Replace("{*aspxlist*}", service.CreateAspxList(t, cols));
                aspxcode = aspxcode.Replace("{*aspxedit*}", service.CreateAspxEdit(t, cols));
                aspxcode = aspxcode.Replace("{*aspxview*}", service.CreateAspxInfo(t, cols));
                aspxcode = aspxcode.Replace("{*aspxserarch*}", service.CreateAspxQuery(t, cols));

                string aspxName=service.GetCodeFileName( t.Name,PageType.Web);

                //生成aspx文件
                string path = GetFileName(string.Format(@"{0}\Pages\{1}\{2}.aspx", GetProjectPath(proj), this.BussinessName, aspxName));
                WriteFile(path, aspxcode);
                if (isWrite)
                {
                    //添加至解决方案
                    proj.ProjectItems.AddFromFile(path);
                }

                //生成aspxcs文件
                string aspxCsCode = ConvertResult(service.CreateAspxCs(t));
                //合并输出
                aspxCsCode = aspxCsCode.Replace("{*aspxcscmdobject*}", service.CreateAspxCsQuery(t, cols));
                aspxCsCode = aspxCsCode.Replace("{*aspxcsedit*}", service.CreateAspxCsEdit(t, cols));
                aspxCsCode = aspxCsCode.Replace("{*aspxcsview*}", service.CreateAspxCsInfo(t, cols));
                aspxCsCode = aspxCsCode.Replace("{*aspxcssave*}", service.CreateAspxCsSave(t, cols));

                path = GetFileName(string.Format(@"{0}\Pages\{1}\{2}.aspx.cs", GetProjectPath(proj), this.BussinessName, aspxName));
                WriteFile(path, aspxCsCode);
                if (isWrite)
                {
                    //添加至解决方案
                    proj.ProjectItems.AddFromFile(path);
                }

                //生成aspxcs.designer文件
                string aspxdesignerCode = ConvertResult(service.CreateAspxDesignerCs(t, cols));
                path = GetFileName(string.Format(@"{0}\Pages\{1}\{2}.aspx.designer.cs", GetProjectPath(proj), this.BussinessName, aspxName));
                WriteFile(path, aspxdesignerCode);
                if (isWrite)
                {
                    //添加至解决方案
                    proj.ProjectItems.AddFromFile(path);
                }

                if (isWrite)
                {
                    //写Ioc配置文件
                    string iocCode = ConvertResult(service.CreateIocConfig(t));

                    WriteIocConfig(proj, iocCode);
                }

                ShowMsg("{0} {1} web 生成完毕。", t.Name, t.Description);

            });        
        }

        /// <summary>
        /// 写入Ioc文件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tableName"></param>
        private void WriteIocConfig(Project proj, string config)
        {
            string path = string.Format(@"{0}\Configuration\", GetProjectPath(proj));
            string [] pathList= Directory.GetFiles(path, "*.config", SearchOption.TopDirectoryOnly);
            foreach(string configPath in pathList)
            {
                //默认取第一个
                string xmlData = string.Empty;
                using (StreamReader sr = new StreamReader(configPath, Encoding.Default))
                {
                    xmlData = sr.ReadToEnd();                  
                }
                int index = xmlData.IndexOf("</components>");
                if ( index> 0 && xmlData.IndexOf(config)<0)
                {
                    //写入配置文件
                    xmlData=xmlData.Insert(index - 1, config);

                    using (StreamWriter sw = new StreamWriter(configPath, false, Encoding.Default))
                    {
                        sw.WriteLine(xmlData);
                        sw.Write(Environment.NewLine);
                    }
                }
            }
        }
      
        #endregion

        private bool IsValidate(List<CodeModel> models, List<string> tables)
        {
            bool isValidate = true;


            Solution2 soln = (Solution2)EnvConfig.ApplicationObject.Solution;
            //获取解决方案列表
            Projects projList = soln.Projects;
         
            if (projList.Count == 0)
            {
                ShowMsg("请先打开解决方案！");
                isValidate=false;
            }            
            else if (tables.Count.Equals(0))
            {
                MessageBox.Show("请选择数据表！");
                isValidate = false;
            }
            else if (models.Count.Equals(0))
            {
                MessageBox.Show("请选择代码模型！");
                isValidate = false;
            }
            else if (models.Exists(t => string.IsNullOrEmpty(t.ProjectName)))
            {
                MessageBox.Show("请选择解决方案！");
                isValidate = false;
            }
          
            return isValidate;
        }

        /// <summary>
        /// 获取选择模型表
        /// </summary>
        /// <returns></returns>
        private List<CodeModel> GetSelectModels()
        {
            List<CodeModel> models = new List<CodeModel>();
            foreach (DataGridViewRow row in dgv_Models.Rows)
            {
                DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells["Col_Solution"];
                //获取模型名称
                string modelName = row.Cells["Col_Name"].Value.ToString();
                //是否选择
                bool isSelect = row.Cells["Col_Select"].Value != null ? Convert.ToBoolean(row.Cells["Col_Select"].Value) : false;

                string prjName = cell.Value.ToString();
                if (isSelect)
                {
                    models.Add(new CodeModel { IsSelect = isSelect, ProjectName = prjName, ModelName = modelName });
                }
            }
            return models;
        }

        /// <summary>
        /// 获取选择数据表
        /// </summary>
        /// <returns></returns>
        private List<string> GetSelectTables()
        {
            List<string> selectItems = new List<string>();
            for (int i = 0; i < treeView_Tables.Nodes.Count; i++)
            {
                TreeNode node = treeView_Tables.Nodes[i];
                if (node.Tag != null && node.Checked)
                {
                    selectItems.Add(node.Tag.ToString());
                }
            }
            return selectItems;
        }

        public class CodeType
        {
            public const string SqlServerData = "SqlServer.Data";
            public const string SqlServerBusinessImplement = "SqlServer.BusinessImplement";
            public const string DataExchange = "DataExchange";
            public const string DataContract = "DataContract";
            public const string ServiceContract = "ServiceContract";
            public const string ServiceImplement = "ServiceImplement";
            public const string CoreService = "CoreService";
            public const string Web = "Web";

        }
    }
}
